package com.citycloud.ccuap.tc.sync.service.impl;

import com.citycloud.ccuap.framework.exception.AppAssert;
import com.citycloud.ccuap.framework.exception.ApplicationException;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncType;
import com.citycloud.ccuap.tc.sync.constant.MqType;
import com.citycloud.ccuap.tc.sync.handle.MessageHandleFactory;
import com.citycloud.ccuap.tc.sync.service.IMessageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MessageService implements IMessageService {

    @Value("${tc.msmq:}")
    private String mqType;

    private static final Map<String, String> CONFIG_HANDLE_MAP;

    static {
        // 初始化已实现MQ处理方式
        CONFIG_HANDLE_MAP = new HashMap<>();
        CONFIG_HANDLE_MAP.put(MqType.ACTIVEMQ.getValue(), "com.citycloud.ccuap.tc.sync.handle.ActiveMqHandle");
        CONFIG_HANDLE_MAP.put(MqType.KAFKA.getValue(), "com.citycloud.ccuap.tc.sync.handle.KafkaHandle");
    }

    private static MessageHandleFactory instance;

    /**
     * 根据配置的文件系统类型获取相应处理方式
     *
     * @return
     * @throws Exception
     */
    private MessageHandleFactory getHandleFactory() throws Exception {
        if (instance == null) {
            AppAssert.isTrue(MqType.contains(mqType), "不支持的MQ类型！");
            Class<?> c = Class.forName(CONFIG_HANDLE_MAP.get(mqType));
            return (MessageHandleFactory) c.newInstance();
        }
        return instance;
    }

    @Override
    public void sendMessageByTopic(Object message,String topicName) {
        try {
            MessageHandleFactory handleFactory = this.getHandleFactory();
            handleFactory.sendMessage(topicName, message);
        } catch (Exception e) {
            throw new ApplicationException("消息发送失败");
        }
    }
}
